package com.example.demo.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.entity.BookAssist;
import com.example.demo.entity.BookComment;
import com.example.demo.entity.BookCore;
import com.example.demo.entity.BookRecommend;
import com.example.demo.entity.BookType;
import com.example.demo.entity.UserInforTourist;
import com.example.demo.serviceimpl.BookAssistServiceImpl;
import com.example.demo.serviceimpl.BookCommentServiceImpl;
import com.example.demo.serviceimpl.BookCoreServiceImpl;
import com.example.demo.serviceimpl.BookRecommendServiceImpl;
import com.example.demo.serviceimpl.BookTypeServiceImpl;
import com.example.demo.serviceimpl.UserInforTouristServiceImpl;

/**
 * 控制层
 * 
 * @author wang
 */
@RestController
@RequestMapping("/book")
public class BookController {

	@Autowired
	private BookCoreServiceImpl bookCoreServiceImpl;

	@Autowired
	private BookTypeServiceImpl bookTypeServiceImpl;

	@Autowired
	private BookRecommendServiceImpl bookRecommendServiceImpl;

	@Autowired
	private BookCommentServiceImpl bookCommentServiceImpl;

	@Autowired
	private BookAssistServiceImpl bookAssistServiceImpl;

	@Autowired
	private UserInforTouristServiceImpl userInforTouristServiceImpl;

	/**
	 * @apiDefine book 查询所有图书
	 */

	/**
	 * 
	 * @apiVersion 1.0.0
	 * @apiDescription 查询书的信息接口
	 * @api {get} http://192.168.2.211:8080/book/book 查询书的信息接口
	 * @apiParam {int} id 书的id（必传）
	 * @apiSuccessExample Request-Example:成功
	 * 
	 *                    { errorCode:200, message:'success',data:{} }
	 * @apiSuccessExample Request-Example:失败
	 * 
	 *                    {errorCode:400, message:'查询失败', data:{} }
	 * @apiSuccess {String} errorCode 200（ 成功结果码）
	 * @apiSuccess {String} errorCode 400 （失败结果码）
	 * @apiGroup Book
	 * @apiSampleRequest http://192.168.2.211:8080/book/book?id=3&userId=1034006
	 * @param request
	 * @return
	 */

	/**
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/book")
	public JSONObject BookNameAndEnglishName(HttpServletRequest request) {

		JSONObject jsonObject = new JSONObject();
		String id = request.getParameter("id");
		String userId = request.getParameter("userId");

		if (id == null) {
			jsonObject.put("errorCode", 400);
			jsonObject.put("message", "请输入id");
			return jsonObject;
		}

		if (userId == null) {
			jsonObject.put("errorCode", 400);
			jsonObject.put("message", "请输入userId");
			return jsonObject;
		}

		// 触发这个接口。数据库pageview字段增加1.。。加一是根据书的id来增加相应的阅读量
		bookCoreServiceImpl.increaseTheNum(Integer.parseInt(id));

		// 查找书的内容，简介
		BookCore result = bookCoreServiceImpl.BookNameandEnglishName(Integer.parseInt(id));
		if (result == null) {
			jsonObject.put("errorCode", 404);
			jsonObject.put("message", "没有相关信息");
			return jsonObject;
		}

		// 查找输的类型
		BookType bookType = bookTypeServiceImpl.bookTypeId(result.getType_id());

		// 书推荐
		List<BookRecommend> bookRecommend = bookRecommendServiceImpl.recommendWihtContent(Integer.parseInt(id));

		// 根据书id差评论集合
		List<BookComment> bookCommentList = bookCommentServiceImpl.FindBookId(result.getId());
		if (bookCommentList == null) {
			jsonObject.put("errorCode", 404);
			jsonObject.put("message", "没有相关信息");
			return jsonObject;
		}
		/**
		 * 把回复放到评论里面
		 */
		for (int i = 0; i < bookCommentList.size(); i++) {
			BookComment bookComment1 = bookCommentList.get(i);

			// 根据评论id查找 点赞总数
			int bookAssistNum = bookAssistServiceImpl.selectComentId(bookComment1.getId());
			// 根据评论id查找 回复
			List<BookComment> list = bookCommentServiceImpl.findComentId(bookComment1.getId());
			// 根据评论id查找对应的点赞外键comment_id.和两端的用户id是否相等
			BookAssist bookAssistIdAndUserId = bookAssistServiceImpl.findCommentIdAndUserId(bookComment1.getId(),
					bookComment1.getUser_Id());

			bookComment1.setTagsOrNot(true);
			if (bookAssistIdAndUserId == null) {
				bookComment1.setTagsOrNot(false);
			}
			// 根据评分grade，书的id计算人数
			int number = bookComment1.getGrade();
			// List<String> numberList = new ArrayList<String>();
			if (number != 0) {
				float a = 0;
				float a1 = 0;
				float a2 = 0;
				float a3 = 0;
				float a4 = 0;
				// 计算相应书籍评分不为0的人数
				int dividend = bookCommentServiceImpl.findAccountUserIdNumber(result.getId());
				// 计算各个评分的人数
				a = bookCommentServiceImpl.findCountUserId(9, 10, result.getId());
				a1 = bookCommentServiceImpl.findCountUserId(7, 8, result.getId());
				a2 = bookCommentServiceImpl.findCountUserId(5, 6, result.getId());
				a3 = bookCommentServiceImpl.findCountUserId(3, 4, result.getId());
				a4 = bookCommentServiceImpl.findCountUserId(1, 2, result.getId());
				// 计算各个评分在占总人数的比例
				float c = a / dividend * 100;
				float c1 = a1 / dividend * 100;
				float c2 = a2 / dividend * 100;
				float c3 = a3 / dividend * 100;
				float c4 = a4 / dividend * 100;
				// 计算浮点数
				BigDecimal b = new BigDecimal(c);
				BigDecimal b1 = new BigDecimal(c1);
				BigDecimal b2 = new BigDecimal(c2);
				BigDecimal b3 = new BigDecimal(c3);
				BigDecimal b4 = new BigDecimal(c4);
				// 保留小数点后1位，并四舍五入
				b = b.setScale(1, BigDecimal.ROUND_HALF_UP);
				b1 = b1.setScale(1, BigDecimal.ROUND_HALF_UP);
				b2 = b2.setScale(1, BigDecimal.ROUND_HALF_UP);
				b3 = b3.setScale(1, BigDecimal.ROUND_HALF_UP);
				b4 = b4.setScale(1, BigDecimal.ROUND_HALF_UP);

				String numberList1[] = { b + "%", b1 + "%", b2 + "%", b3 + "%", b4 + "%", };

				result.setNumberList(numberList1);
			}
			bookComment1.setBookReplyCommentList(list);
			bookComment1.setBookAssistAccount(bookAssistNum);
		}
		// 查找相关书的评论总数
		int count = bookCommentServiceImpl.findBookCoreId(result.getId());
		if (count == 0) {
			jsonObject.put("errorCode", 404);
			jsonObject.put("message", "该书没有评论");
			result.setNumberCounts(count);
		}
		// 计算评分的均数
		float ageGrade = bookCommentServiceImpl.findTheAverage(Integer.parseInt(id));
		if (ageGrade == 0) {
			result.setAgeGrade(0);
		}
		System.out.println(ageGrade);

		// 保留评分以为小数
		float num = (float) (Math.round(ageGrade * 10)) / 10;

		System.out.println(num);

		result.setNumberCounts(count);
		result.setTypeName(bookType.getTypeName());
		result.setBookRecommendList(bookRecommend);
		result.setBookCommentList(bookCommentList);
		result.setAgeGrade(num);
		jsonObject.put("date", result);

		jsonObject.put("errorCode", 200);
		jsonObject.put("message", "查询成功");

		return jsonObject;
	}

	/**
	 * @apiDefine insertComments 添加评论接口
	 */

	/**
	 * 
	 * @apiVersion 1.0.0
	 * @apiDescription 查询书的信息接口
	 * @api {get} http://192.168.2.211:8080/book/insertComments 添加评论接口
	 * @apiParam {int} bookId 书的id（必传）
	 * @apiParam {String} content 书的评论（必传）
	 * @apiParam {int} grade 书的评分（必传）
	 * @apiParam {int} userId 用户id（必传）
	 * @apiSuccessExample Request-Example:成功
	 * 
	 *                    { errorCode:200, message:'success',data:{} }
	 * @apiSuccessExample Request-Example:失败
	 * 
	 *                    {errorCode:400, message:'查询失败', data:{} }
	 * @apiSuccess {String} errorCode 200（ 成功结果码）
	 * @apiSuccess {String} errorCode 400 （失败结果码）
	 * @apiGroup InsertComents
	 * @apiSampleRequest http://192.168.2.211:8080/book/insertComments?bookId=3&content=ssss1&grade=9&userId=1034006
	 * @param request
	 * @return
	 */

	/**
	 * 添加评论
	 * 
	 * @param bookComment
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/insertComments")
	public JSONObject insertComments(BookComment bookComment, HttpServletRequest request) throws Exception {
		JSONObject jsonObject = new JSONObject();
		String bookId = request.getParameter("bookId");
		String content = request.getParameter("content");
		String grade = request.getParameter("grade");
		String userId = request.getParameter("userId");
		if (bookId == null) {
			jsonObject.put("errorcode", 400);
			jsonObject.put("message", "输入书的bookId");
			return jsonObject;
		}
		if (content == null) {
			jsonObject.put("errorcode", 400);
			jsonObject.put("message", "评论输入评论");
			return jsonObject;
		}

		if (grade == null) {
			jsonObject.put("errorcode", 400);
			jsonObject.put("message", "评论输入评分");
			return jsonObject;
		}

		if (1 > Integer.parseInt(grade) || Integer.parseInt(grade) > 10) {
			jsonObject.put("errorcode", 400);
			jsonObject.put("message", "评论输入评分1~10");
			return jsonObject;
		}
		if (userId == null || "".equals(userId)) {
			jsonObject.put("errorcode", 400);
			jsonObject.put("message", "评论输入userId");
			return jsonObject;
		}

		// 查找书的内容，简介
		BookCore result = bookCoreServiceImpl.BookNameandEnglishName(Integer.parseInt(bookId));

		if (result == null) {
			jsonObject.put("errorcode", 404);
			jsonObject.put("message", "未找到相关的书籍");
			return jsonObject;
		}

		// 一个获取用户的服务。比如返回一个user
		UserInforTourist UserInforTourist = userInforTouristServiceImpl.findUserId(Integer.parseInt(userId));
		if (UserInforTourist == null) {
			jsonObject.put("errorcode", 404);
			jsonObject.put("message", "没有相关用户");
			return jsonObject;
		}
		// 根据书id查找评论
		List<BookComment> list = bookCommentServiceImpl.findUseridAndBookid(result.getId());
		if (list == null) {
			jsonObject.put("errorcode", 404);
			jsonObject.put("message", "该书没有评论！");
			return jsonObject;
		}
		System.out.println(list.size());
		/**
		 * 根据书的id,循环遍历评论id，和评论id
		 */
		for (int i = 0; i < list.size(); i++) {
			// 遍历评论
			BookComment bookComment1 = list.get(i);
			int user = bookComment1.getUser_Id();
			System.out.println("------------------------------------------------------" + bookComment1);
			// 根据获取的评论id查询点赞数量
			int bookAssistAccount = bookAssistServiceImpl.selectComentId(bookComment1.getId());
			BookAssist bookAssistOne = new BookAssist();
			bookAssistOne.setUser_id(user);
			bookAssistOne.setBookAssistAccount(bookAssistAccount);
			jsonObject.put("date", bookAssistOne);

		}

		// 添加记录
		bookComment.setContent(content);
		bookComment.setGrade(Integer.parseInt(grade));
		bookComment.setCreateTime(new Date());// 创建时间
		bookComment.setBook_core_id(result.getId());
		bookComment.setUser_Id(UserInforTourist.getId());
		bookComment.setType(0);// 0,评论,大于1,回复的评论id
		// ----------------------------------------------------------------------------------------------
		// 查询评论下的点赞总数
		// int bookAssistAccount =
		// bookAssistServiceImpl.selectComentId(Integer.parseInt(list.));
		//
		// // 查询当前BookAssist的id
		// BookAssist bookAssist =
		// bookAssistServiceImpl.selectComent(Integer.parseInt(id));
		//
		// // 查询当前用户是否给评论点过赞
		// BookComment bookCommentAccount =
		// bookCommentServiceImpl.findCommentIdAndInfo(bookAssist.getId());
		// if (bookCommentAccount == null) {
		// jSONObject.put("errorcode", 400);
		// jSONObject.put("message", "该用户没有点赞");
		// //jSONObject.put("bookAssistAccount", bookAssistAccount);
		// return jSONObject;
		// }
		int count = bookCommentServiceImpl.insertCommentId(bookComment);
		if (count < 1) {
			jsonObject.put("errorcode", 400);
			jsonObject.put("message", "评论失败");
			return jsonObject;
		}
		jsonObject.put("errorcode", 200);
		jsonObject.put("message", "评论成功！");
		return jsonObject;
	}

	/**
	 * @apiDefine select 点赞接口
	 */

	/**
	 * 
	 * @apiVersion 1.0.0
	 * @apiDescription 查询书的信息接口
	 * @api {get} http://192.168.2.211:8080/book/select 点赞接口
	 * @apiParam {int} comentId 评论comentId（必传）
	 * @apiParam {int} userId 用户id（必传）
	 * @apiSuccessExample Request-Example:成功
	 * 
	 *                    { errorCode:200, message:'success',data:{} }
	 * @apiSuccessExample Request-Example:失败
	 * 
	 *                    {errorCode:400, message:'查询失败', data:{} }
	 * @apiSuccess {String} errorCode 200（ 成功结果码）
	 * @apiSuccess {String} errorCode 400 （失败结果码）
	 * @apiGroup Select
	 * @apiSampleRequest http://192.168.2.211:8080/book/select?comentId=531&userId=1034002
	 * @param request
	 * @return
	 */
	/**
	 * 点赞接口....
	 * 
	 * @param request
	 * @param bookAssist
	 * @return
	 */
	@RequestMapping("/select")
	public JSONObject addSupportAndLike(HttpServletRequest request, BookAssist bookAssist) {

		String comentId = request.getParameter("comentId");
		String userId = request.getParameter("userId");
		JSONObject jsonObject = new JSONObject();
		JSONObject jsonObjectOne = new JSONObject();
		if (comentId == null || "".equals(comentId)) {
			jsonObject.put("errorcode", 400);
			jsonObject.put("messsage", "请输入comentId");
			return jsonObject;
		}
		if (userId == null) {
			jsonObject.put("errorcode", 400);
			jsonObject.put("message", "输入用户id");
			return jsonObject;
		}

		// 查找相关用户Id
		UserInforTourist userInforTouristId = userInforTouristServiceImpl.findUserId(Integer.parseInt(userId));

		if (userInforTouristId == null) {
			jsonObject.put("errorcode", 400);
			jsonObject.put("message", "未找到相关用户");
			return jsonObject;
		}

		// 查询相同的人点赞时间一天内的数据
		Integer book = bookAssistServiceImpl.selectComentIdByTime(Integer.parseInt(comentId), Integer.parseInt(userId));
		if (book != null) {
			// 删除相同的点赞记录
			int a = bookAssistServiceImpl.deleteComent(Integer.parseInt(comentId), Integer.parseInt(userId));
			if (a == 1) {
				int count = bookAssistServiceImpl.selectComentId(Integer.parseInt(comentId));
				jsonObject.put("errorcode", 200);
				jsonObject.put("message", "取消点赞成功");
				jsonObject.put("count", count);
				return jsonObject;
			} else {
				jsonObject.put("errorcode", 400);
				jsonObject.put("message", "取消点赞失败");
				return jsonObject;
			}
		}
		// 根据comentId查询评论
		BookComment bookCommentId = bookCommentServiceImpl.findBookCommentOne(Integer.parseInt(comentId));
		System.out.println(bookCommentId);
		// 判断评论id是否存在评论里面
		if (bookCommentId == null) {
			jsonObject.put("errorcode", 404);
			jsonObject.put("message", "没有该记录");
			return jsonObject;
		}
		// 判断该记录是否为评论
		if (bookCommentId.getType() > 0) {
			jsonObject.put("errorcode", 404);
			jsonObject.put("message", "没有该条评论!或者该记录为评论回复");
			return jsonObject;
		}

		bookAssist.setComment_id(bookCommentId.getId());
		bookAssist.setUser_id(userInforTouristId.getId());
		bookAssist.setCreateTime(new Date());// 创建时间

		// 添加点赞人的记录
		int num = bookAssistServiceImpl.insertComent(bookAssist);
		if (num < 1) {
			jsonObject.put("errorcode", 400);
			jsonObject.put("messsage", "添加失败");
			return jsonObject;
		}

		// 统计点赞总数
		int count = bookAssistServiceImpl.selectComentId(Integer.parseInt(comentId));

		if (count < 1) {
			jsonObject.put("errorcode", 200);
			jsonObject.put("messsage", "点赞书为0");
			return jsonObject;
		}
		System.out.println("------------------------------------------" + bookAssist);
		bookAssist.setBookAssistAccount(count);
		jsonObjectOne.put("date", count);
		jsonObjectOne.put("bookAssistUserId", bookAssist.getUser_id());
		jsonObject.put("date", jsonObjectOne);
		jsonObject.put("errorcode", 200);
		jsonObject.put("messsage", "点赞成功");
		return jsonObject;
	}

	/**
	 * @apiDefine comment 评论回复接口
	 */

	/**
	 * 
	 * @apiVersion 1.0.0
	 * @apiDescription 查询书的信息接口
	 * @api {get} http://192.168.2.211:8080/book/comment 评论回复接口
	 * @apiParam {int} bookId 书的bookId（必传）
	 * @apiParam {int} userId 用户userId（必传）
	 * @apiParam {int} commentId 评论commentId（必传）
	 * @apiParam {String} content 评论content的内容（必传）
	 * @apiSuccessExample Request-Example:成功
	 * 
	 *                    { errorCode:200, message:'success',data:{} }
	 * @apiSuccessExample Request-Example:失败
	 * 
	 *                    {errorCode:400, message:'查询失败', data:{} }
	 * @apiSuccess {String} errorCode 200（ 成功结果码）
	 * @apiSuccess {String} errorCode 400 （失败结果码）
	 * @apiGroup Comment
	 * @apiSampleRequest http://192.168.2.211:8080/book/comment?commentId=531&userId=1000001&bookId=3&content=13131
	 * @param request
	 * @return
	 */

	/**
	 * 评论回复
	 * 
	 * @param bookComment
	 * @param request
	 * @return
	 */
	@RequestMapping("/comment")
	public JSONObject resultComentAndUserId(BookComment bookComment, HttpServletRequest request) {
		JSONObject jsonObject = new JSONObject();
		// 传用户id 书id，评论id
		String bookId = request.getParameter("bookId");
		String userId = request.getParameter("userId");
		String commentId = request.getParameter("commentId");
		if (commentId == null) {
			jsonObject.put("errorcode", 400);
			jsonObject.put("message", "评论输入commentId");
			return jsonObject;
		}
		if (userId == null) {
			jsonObject.put("errorcode", 400);
			jsonObject.put("message", "输入用户userId");
			return jsonObject;
		}
		if (bookId == null) {
			jsonObject.put("errorcode", 400);
			jsonObject.put("message", "输入书bookId");
			return jsonObject;
		}
		// 查找相关书籍
		BookCore bookCoreId = bookCoreServiceImpl.BookNameandEnglishName(Integer.parseInt(bookId));
		if (bookCoreId == null) {
			jsonObject.put("errorcode", 400);
			jsonObject.put("message", "没有相关书籍");
			return jsonObject;
		}
		// 查找相关用户Id
		UserInforTourist userInforTouristId = userInforTouristServiceImpl.findUserId(Integer.parseInt(userId));

		if (userInforTouristId == null) {
			jsonObject.put("errorcode", 404);
			jsonObject.put("message", "未找到相关用户");
			return jsonObject;
		}

		// 查找评论Id
		BookComment bookCommenId = bookCommentServiceImpl.findCommentIdAndInfo(Integer.parseInt(commentId));
		if (bookCommenId == null) {
			jsonObject.put("errorcode", 404);
			jsonObject.put("message", "未找到相关评论");
			return jsonObject;
		}

		System.out.println(bookCommenId);

		String content = request.getParameter("content");
		if (content == null) {
			jsonObject.put("errorcode", 400);
			jsonObject.put("message", "请输评论入回复");
			return jsonObject;
		}

		if (Integer.parseInt(bookId) != bookCommenId.getBook_core_id()) {
			jsonObject.put("errorcode", 404);
			jsonObject.put("message", "该书没有评论！请重新船输入书的bookId");
			return jsonObject;
		}
		// 查找评论id或回复id
		// BookAssist BookAssist =
		// bookAssistServiceImpl.selectComent(Integer.parseInt(assistId));

		bookComment.setBook_core_id(Integer.parseInt(bookId));
		bookComment.setUser_Id(Integer.parseInt(userId));
		bookComment.setCreateTime(new Date());
		bookComment.setContent(content);
		bookComment.setType(bookCommenId.getId());
		bookComment.setGrade(0);

		// 根据Type查找评论
		BookComment bookCommentAlert = bookCommentServiceImpl.findCommentIdAndInfo(bookCommenId.getId());
		if (bookCommentAlert == null) {
			jsonObject.put("errorcode", 404);
			jsonObject.put("message", "该书没有评论!");
			return jsonObject;
		}
		bookComment.setReguseId(bookCommentAlert.getUser_Id());

		int count = bookCommentServiceImpl.insertCommentId(bookComment);
		if (count < 1) {
			jsonObject.put("errorcode", 400);
			jsonObject.put("message", "回复评论失败");
			return jsonObject;
		}
		jsonObject.put("date", bookComment);
		jsonObject.put("errorcode", 200);
		jsonObject.put("message", "回复成功！");
		return jsonObject;
	}

	public static void main(String[] args) {
		float a = 9;
		float b = 7;
		float c = b / a * 100;
		BigDecimal d = new BigDecimal(c);
		d = d.setScale(1, BigDecimal.ROUND_HALF_UP);
		System.out.println(d + "%");
	}

}
